﻿<%@ WebHandler Language="C#" Class="Image" %>

using System;
using System.Web;
using System.Drawing;

public class Image : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/JPEG";
        
        // 返回web服务器上的指定虚拟路径相对应的物理文件路径
        string fullPath = HttpContext.Current.Server.MapPath("TuPian.jpg");

        using (Bitmap bitmap = new Bitmap(fullPath))
        {
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                // 直接访问该图片时。
                if (context.Request.UrlReferrer == null)
                {
                    g.Clear(Color.White);
                    g.DrawString("禁止直接浏览该图片，/n请在页面中查看!", new Font("宋体", 20, FontStyle.Italic), Brushes.Red, new PointF(0, 0));
                }
                else if (context.Request.UrlReferrer.Host != "localhost")
                {
                    g.Clear(Color.White);
                    g.DrawString("本图片只限内容访问!", new Font("宋体", 20, FontStyle.Italic), Brushes.Red, new PointF(0, 0));
                }
            }
            
            bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}